package Components
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	
	import mx.core.UIComponent;
	import mx.managers.FocusManager;
	
	public class BalloonPanel extends DraggablePanel
	{
		[Bindable]
		[Inspectable]
		public var Speaker:DisplayObject;
		
		[Bindable]
		[Inspectable]
		public var Layer:DisplayObjectContainer;
		
		protected var showing:Boolean;
		protected var lastSpeakerLocation:Point;
		protected var lastLocation:Point;
		protected var lastSize:Point;
		
		public function BalloonPanel()
		{
			super();
			addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
		}
		
		public override function move(x:Number, y:Number):void
		{
			super.move(x,y);
			lastLocation = new Point(x,y);
		}
		protected function mouseDownHandler(evt:Event):void
		{
			watchForDrag();
		}
		protected override function keyDownHandler(evt:KeyboardEvent):void
		{
			super.keyDownHandler(evt);
			if(evt.keyCode == Keyboard.ESCAPE)
				Hide();
		}
		public function Show():void
		{
			if(showing) return;
			Layer.addChild(this);
			
			if(!focusManager)
				focusManager = new FocusManager(this, false);
				
			this.setFocus();
			Position();
			showing = true;
		}
		public function Hide():void
		{
			if(!showing) return;
			Layer.removeChild(this);
			showing = false;
		}
		public function Toggle():void
		{
			if(showing)
				Hide();
			else
				Show();
		}
		
		protected function Position():void
		{
			if(lastSpeakerLocation)
				if(lastSpeakerLocation.x != Speaker.x || lastSpeakerLocation.y != Speaker.y)
					lastLocation = null;
			lastSpeakerLocation = new Point(Speaker.x, Speaker.y);
			
			if(lastSize)
				setActualSize(lastSize.x, lastSize.y);
			else
				setActualSize(getExplicitOrMeasuredWidth(), getExplicitOrMeasuredHeight());
			
			if(lastLocation)
				move(lastLocation.x, lastLocation.y);
			else
			{
				var opoint:Point = Speaker.localToGlobal(new Point(0,0));
				if(Layer is UIComponent)
					opoint = UIComponent(Layer).globalToContent(opoint);
				else
					opoint = Layer.globalToLocal(opoint);
				var npoint:Point = new Point();
				//first try to position the comments to the right, if that fails go left
				npoint.x = opoint.x + Speaker.width + 20;
				if(npoint.x + width > Layer.width)
					npoint.x = opoint.x - width - 20;
				
				npoint.y = opoint.y;
				if(npoint.y + height > Layer.height)
					npoint.y = screen.height - height;
				
				move(npoint.x, npoint.y);
			}			
		}
	}
}